using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Skywalker.Fluently;

namespace Skywalker.Web.Mvc.ViewComponents
{
    public class Renderer : IRenderer
    {
        public HtmlHelper Html { get; set; }

        public Renderer(HtmlHelper html)
        {
            Html = html;
        }

        public IHtmlString RenderComponent<T>(T component, string viewName = null) where T : IViewComponent
        {
            viewName     = viewName ?? GetViewName(component);
            var result   = ViewEngines.Engines.FindPartialView(new ControllerContext(Html.ViewContext.RequestContext, Html.ViewContext.Controller), viewName);
            var sb       = new StringBuilder();

            using (var writer = new HtmlTextWriter(new IndentedTextWriter(new StringWriter(sb))))
            {
                Html.ViewContext.ViewData.Model = this;

                if (result.View != null)
                {
                    result.View.Render(Html.ViewContext, writer);
                }
                else
                {
                    RenderDefaultView(writer);
                }
            }

            return new HtmlString(sb.ToString());
        }

        public IHtmlString RenderComponent<TBuilder>(Action<TBuilder> component, string viewName = null) where TBuilder : IBuilder, new()
        {
            var builder = Factory.Default.CreateAndExecuteBuilder(component);
            return RenderComponent(builder.Component);
        }

        private static void RenderDefaultView(TextWriter writer)
        {
            var tag = new TagBuilder("div");
            writer.WriteLine(tag.ToString());
        }

        private static string GetViewName<T>(T component) where T: IViewComponent
        {
            return !string.IsNullOrWhiteSpace(component.ViewName) ? component.ViewName : typeof(T).Name;
        }

    }
}